package util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

class Spelling {
	private final HashMap<String, Integer> words = new HashMap<String, Integer>();

	private static Spelling instance;

	private Spelling(String file) throws IOException {
		InputStream is = new BufferedInputStream(new FileInputStream(file));
		Reader reader = new InputStreamReader(is, "ISO-8859-1");
		BufferedReader in = new BufferedReader(reader);
		for (String temp = ""; temp != null; temp = in.readLine()) {
			System.out.println(temp);
			words.put(temp, 1);
		}
		in.close();
	}

	public static Spelling getInstance() {
		if (instance == null) {
			try {
				instance = new Spelling(Constants.DICTIONARY_FILE);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return instance;
	}

	private final ArrayList<String> edits(String word) {
		ArrayList<String> result = new ArrayList<String>();
		for (int i = 0; i < word.length(); ++i)
			result.add(word.substring(0, i) + word.substring(i + 1));
		for (int i = 0; i < word.length() - 1; ++i)
			result.add(word.substring(0, i) + word.substring(i + 1, i + 2)
					+ word.substring(i, i + 1) + word.substring(i + 2));
		for (int i = 0; i < word.length(); ++i)
			for (char c = 'a'; c <= 'z'; ++c)
				result.add(word.substring(0, i) + String.valueOf(c)
						+ word.substring(i + 1));
		for (int i = 0; i <= word.length(); ++i)
			for (char c = 'a'; c <= 'z'; ++c)
				result.add(word.substring(0, i) + String.valueOf(c)
						+ word.substring(i));
		return result;
	}

	public final String correct(String word) {
		if (words.containsKey(word))
			return word;
		ArrayList<String> list = edits(word);
		HashMap<Integer, String> candidates = new HashMap<Integer, String>();
		for (String s : list)
			if (words.containsKey(s))
				candidates.put(words.get(s), s);
		if (candidates.size() > 0)
			return candidates.get(Collections.max(candidates.keySet()));
		for (String s : list)
			for (String w : edits(s))
				if (words.containsKey(w))
					candidates.put(words.get(w), w);
		return candidates.size() > 0 ? candidates.get(Collections
				.max(candidates.keySet())) : word;
	}

	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		while (true) {
			System.out.print("palavra: ");
			String linha = bf.readLine();
			if (linha.equals("")) {
				break;
			}
			System.out.println("Did you mean? "
					+ Spelling.getInstance().correct(linha));
		}
	}
}